package org.jtb.quickr;

import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.Logger;

class PhotoUrl extends FlickrUrl {
    private static Logger logger = Logger.getLogger(PhotoUrl.class.getName());
    
    private String serverId;
    private String photoId;
    private String secret;
    private PhotoSize size;
    private String ext;
    
    /**
     * Construct a photo URL to a scaled (sized) photo.
     * <p>
     * The size of the scaled photo must be specified. The scaled photo will have
     * an extension of "jpg".
     */
    public PhotoUrl(String staticUrl, String serverId, String photoId, String secret, PhotoSize size) throws QuickrException {
        this(staticUrl, serverId, photoId, secret, size, "jpg");
    }
    
    /**
     * Construct a photo URL to the original photo.
     * <p>
     * The original photo's extension must be specified.
     */
    PhotoUrl(String staticUrl, String serverId, String photoId, String secret, String ext) throws QuickrException {
        this(staticUrl, serverId, photoId, secret, PhotoSize.ORIGINAL, ext);
    }
    
    PhotoUrl(String staticUrl, String serverId, String photoId, String secret, PhotoSize size, String ext) throws QuickrException {
        super(staticUrl);
        
        this.serverId = serverId;
        this.photoId = photoId;
        this.secret = secret;
        this.size = size;
        this.ext = ext;
    }
    
    protected URL buildUrl() throws QuickrException {
        StringBuffer b = new StringBuffer(32);
        
        b.append(getBaseUrl());
        b.append("/");
        b.append(serverId);
        b.append("/");
        b.append(photoId);
        b.append("_");
        b.append(secret);
        if (!size.equals(PhotoSize.MEDIUM)) {
            b.append("_");
            b.append(size.toString());
        }
        b.append(".");
        b.append(ext);
        
        try {
            URL url = new URL(b.toString());
            if (logger.isDebugEnabled()) {
                logger.debug("url: " + url);
            }            
            return url;
        } catch (MalformedURLException mfue) {
            throw new QuickrException("could not construct photo URL", mfue);
        }
    }
}
